<template>
  <!-- 最外层容器 -->
  <section class="todoapp">
    <!-- 头部 -->
    <Header v-model:todos="todos"/>
    <!-- 代办列表 -->
    <List v-model:todos="todos" v-model:filteredTodos="filteredTodos"/>
    <!-- 底部 -->
    <Footer v-model:todos="todos" v-model:remainNum="remainNum" v-model:visiblity="visiblity" @removeAll="removeCompleted"/>
  </section>
</template>

<script setup>
import { ref, computed, watchEffect, watch } from "vue";
import Header from "./components/Header.vue";
import List from "./components/List.vue";
import Footer from "./components/Footer.vue";

// 每一项的待办事项结构如下
// [{id: 1,title: 'xxx', completed: false}]

const STORAGE_KEY = "todo-list";

// 尝试从本地缓存中获取，如果没有数据则使用空数组(第一次)
const todos = ref(JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]"));
// 默认显示所有待办事项 取值：'all' 'active' 'completed'
const visiblity = ref("all");

const filters = {
  all: (todos) => todos,
  active: (todos) => todos.filter((todo) => !todo.completed),
  completed: (todos) => todos.filter((todo) => todo.completed),
};

const filteredTodos = computed(() => filters[visiblity.value](todos.value));
// 未完成项
const remainNum = computed(() => filters["active"](todos.value).length);


function removeCompleted() {
  if (window.confirm("确定要删除所有已完成的待办事项吗?")) {
    // todos.value = filters["active"](todos.value);
  }
}

// 监听hash变化
window.addEventListener("hashchange", onHashChange);
function onHashChange() {
  const route = window.location.hash.replace(/#\//, "");
  if (filters[route]) {
    visiblity.value = route;
  } else {
    window.location.hash = "";
    visiblity.value = "all";
  }
}

// 持久化存储
watchEffect(() => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(todos.value));
});
</script>

<style scoped>
@import "./assets/todo.css";

.todoapp {
  background: #fff;
  margin: 130px auto;
  position: relative;
  box-shadow:
    0 2px 4px 0 rgba(0, 0, 0, 0.2),
    0 25px 50px 0 rgba(0, 0, 0, 0.1);
  width: 800px;
}
</style>
